
module State.Json() where

import Text.JSON
import Text.JSON.Generic(toJSON, fromJSON)
import State.Database
import Control.Applicative ((<$>),(<*>))

instance JSON Language where
    showJSON = toJSON
    readJSON = fromJSON

programCodeKey = "programCode"
programLangKey = "programLanguage"

instance JSON Program where
    showJSON Program {programCode, programLanguage}
        = JSObject $ toJSObject $
            [ (programCodeKey, showJSON programCode)
            , (programLangKey, showJSON programLanguage)]
    readJSON (JSObject obj) = Program
                        <$> valFromObj programCodeKey obj
                        <*> valFromObj programLangKey obj
    readJSON _ = Error $ "Cannot parse a Program: it should be a JSObject"

problemNameKey = "problemName"
problemStatementKey = "problemStatement"
testValidatorKey = "testValidator"
referenceSolutionKey = "referenceSolution"

instance JSON ProblemInfo where
    showJSON ProblemInfo {problemName, problemStatement, testValidator, referenceSolution}
        = JSObject $ toJSObject
                     [(problemNameKey, showJSON problemName)
                     ,(problemStatementKey, showJSON problemStatement)
                     ,(testValidatorKey, showJSON testValidator)
                     ,(referenceSolutionKey, showJSON referenceSolution)]
    readJSON (JSObject obj) =
                    ProblemInfo
                    <$> valFromObj problemNameKey obj
                    <*> valFromObj problemStatementKey obj
                    <*> valFromObj testValidatorKey obj
                    <*> valFromObj referenceSolutionKey obj
    readJSON _ = Error $ "Cannot parse a ProblemInfo: it should be a JSObject"
